package ${org}.${project}.common.dao.impl;

import org.springframework.stereotype.Repository;
import ${org}.${project}.common.model.${modelName?cap_first};
import ${org}.${project}.common.model.GridResponse;
import org.apache.log4j.Logger;
import org.apache.commons.lang.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;

@Repository
public class ${modelName?cap_first}DaoImpl implements ${modelName?cap_first}Dao {
	private Logger logger = Logger.getLogger(this.getClass());
	@Resource(name = "pageService")
	private PageService pageService;

	@Resource(name = "jdbcTemplate")
	private JdbcTemplate jdbcTemplate;

	@Resource(name = "namedParameterJdbcTemplate")
	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	private final static String FIND_SQL = "SELECT " +
		"<#list modelColumns as column><#if (column_index > 0)>,</#if>${column.name}</#list> " +
		"FROM   ${tableName} ";
	private final static String FIND_SQL_BY_ID = "SELECT " +
		"<#list modelColumns as column><#if (column_index > 0)>,</#if>${column.name}</#list> " +
		"FROM   ${tableName} " +
    	"WHERE ID=:id ";
	private final static String INSERT_SQL = " INSERT INTO ${tableName} ( <#list modelColumns as column><#if (column_index > 0)>,</#if>${column.name}</#list>) " +
		"values (<#list modelColumns as column><#if (column_index > 0)>,</#if>:${column.propertyName}</#list>)" ;
	private final static String DELETE_SQL_BY_ID = "UPDATE ${tableName}  SET STATUS = " + StatusEnum.STATUS_DEL.getIndex() + " WHERE ID=:id";
	private final static String UPDATE_SQL_BY_ID = " TODO ";
	/**
	 * 添加${modelComment !}
	 * 
	 * @param ${modelName?uncap_first}
	 */
	@Override
	public void insert(${modelName?cap_first} ${modelName?uncap_first}) throws Exception{
		SqlParameterSource paramSource = new BeanPropertySqlParameterSource(${modelName?uncap_first});
		try {
			namedParameterJdbcTemplate.update(INSERT_SQL, paramSource);
		} catch (DataAccessException e) {
			throw e;
		}
	}
	/**
	 * 删除${modelComment !}
	 * 
	 * @param id
	 */
 	@Override
	public void deleteById(String id) throws Exception{
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", id);
		try {
			namedParameterJdbcTemplate.update(DELETE_SQL_BY_ID, paramMap);
		} catch (DataAccessException e) {
			throw e;
		}
	}

	/**
	 * 修改${modelComment !}
	 * 
	 * @param id
	 */
 	@Override
	public void updateById(String id) throws Exception{
	}
	
	
	/**
	 * 分页查询${modelComment !}
	 *
	 * @param ${modelName?uncap_first}
	 * @return
	 */
 	@Override
	public GridResponse<${modelName?cap_first}> getPage(${modelName?cap_first} ${modelName?uncap_first}) throws Exception{
		int total = getCount(${modelName?uncap_first});
		List<Object> params = new ArrayList<Object>();
		String sql = getSelectSql(FIND_SQL, ${modelName?uncap_first}, params);
		final String pageSql = pageService.getPageSql(sql, total, ${modelName?uncap_first}.getPage(), ${modelName?uncap_first}.getRows());
		List<${modelName?cap_first}> list = null;
		try {
			list = jdbcTemplate.query(pageSql, params.toArray(), new BeanPropertyRowMapper<${modelName?cap_first}>(${modelName?cap_first}.class));
		} catch (DataAccessException e) {
			throw e;
		}
		GridResponse<${modelName?cap_first}> response = new GridResponse<${modelName?cap_first}>();
		if (list == null) {
			list = new ArrayList<${modelName?cap_first}>();
		}
		response.setRows(list);
		response.setPage(${modelName?uncap_first}.getPage());
		response.setTotal(total);
		return response;
	}
	
	
	/**
	 * 查询${modelComment !}
	 * 
	 * @param id
	 * @return
	 */
 	@Override
    public ${modelName?cap_first} findById(String id) throws Exception{
    	List<${modelName?cap_first}> list = null;
        try {
        	list = jdbcTemplate.query(FIND_SQL_BY_ID, new Object[]{id}, new BeanPropertyRowMapper<${modelName?cap_first}>(${modelName?cap_first}.class));
		} catch (DataAccessException e) {
            throw e;
		}
		if (list != null && list.size() > 0) {
            return list.get(0);
		}
		return null;
	}

   /**
	* 查询总数
	*
    * @param ${modelName?uncap_first}
	* @return
	*/
	@Override
	public int getCount(${modelName?cap_first} ${modelName?uncap_first}) throws Exception{
		List<Object> params = new ArrayList<Object>();
		String sql = getSelectSql(FIND_SQL, ${modelName?uncap_first}, params);
		logger.debug("查询SQL：" + sql);
		sql = "SELECT COUNT(*) TOTAL FROM (" + sql + ")";
		int count = 0;
		try {
			count = jdbcTemplate.queryForObject(sql, params.toArray(), Integer.class);
		} catch (DataAccessException e) {
			throw e;
		}
		return count;
	}
}
